package com.by.arraylist;

/**
 * @version 1.0
 * @Author 彭彦彬
 * @Date 2025/4/9 17:36
 * @注释
 */
public class MyArrayList<E> {
    private static final int DEFAULT_CAPACITY = 10; // 默认初始容量
    private Object[] elements; // 存储元素的数组
    private int size; // 当前元素数量

    public MyArrayList() {
        this(DEFAULT_CAPACITY);
    }

    public MyArrayList(int initialCapacity) {
        if (initialCapacity < 0) {
            throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
        }
        elements = new Object[initialCapacity];
        size = 0;
    }

    /**
     * 添加元素到末尾
     */
    public void add(E element) {
        ensureCapacity(size + 1); // 确保容量足够
        elements[size++] = element; // 将元素添加到最后
    }

    /**
     * 在指定索引处插入元素
     */
    public void add(int index, E element) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
        ensureCapacity(size + 1); // 确保容量足够
        System.arraycopy(elements, index, elements, index + 1, size - index); // 向右移动元素
        elements[index] = element; // 插入新元素
        size++;
    }

    /**
     * 获取指定索引处的元素
     */
    @SuppressWarnings("unchecked")
    public E get(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
        return (E) elements[index];
    }

    /**
     * 删除指定索引处的元素
     */
    public E remove(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
        @SuppressWarnings("unchecked")
        E oldValue = (E) elements[index]; // 保存被删除的元素
        int numMoved = size - index - 1; // 需要移动的元素数量
        if (numMoved > 0) {
            System.arraycopy(elements, index + 1, elements, index, numMoved); // 向左移动元素
        }
        elements[--size] = null; // 清空最后一个位置
        return oldValue;
    }

    /**
     * 获取当前元素数量
     */
    public int size() {
        return size;
    }

    /**
     * 判断是否为空
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 确保容量足够
     */
    private void ensureCapacity(int minCapacity) {
        if (minCapacity > elements.length) {
            grow(minCapacity); // 扩容
        }
    }

    /**
     * 动态扩容
     */
    private void grow(int minCapacity) {
        int oldCapacity = elements.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1); // 容量增加 50%
        if (newCapacity < minCapacity) {
            newCapacity = minCapacity; // 至少满足最小容量需求
        }
        elements = java.util.Arrays.copyOf(elements, newCapacity); // 创建新数组并复制数据
    }

    public static void main(String[] args) {
        MyArrayList<Integer> list = new MyArrayList<>();
        list.add(10);
        list.add(20);
        list.add(30);
        System.out.println(list.get(1));
    }
}